package com.leyou.item.controller;

import com.leyou.page.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryBrandService categoryBrandService;

    //根据id查询品牌
    @GetMapping("/{id}")
    public ResponseEntity<BrandDTO> queryBrandById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(new BrandDTO(brandService.getById(id)));
    }

    //根据品牌id集合查询品牌集合
    @GetMapping("/list")
    public ResponseEntity<List<BrandDTO>> queryBrandsByIds(@RequestParam("ids") List<Long> ids) {
        List<Brand> brands = brandService.listByIds(ids);  //调用mybatispius提供的根据集合查询的方法
        List<BrandDTO> brandDTOS = BrandDTO.convertEntityList(brands); //转换
        return ResponseEntity.ok(brandDTOS);  //返回
    }

    //分页查询品牌
    @GetMapping("page")                            //搜索条件  当前页码  每页条数  默认数值
    public ResponseEntity<PageDTO<BrandDTO>> pageBrands(@RequestParam(value = "key", required = false) String key,
                                                        @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                        @RequestParam(value = "rows", defaultValue = "5") Integer size) {
        PageDTO<BrandDTO> brandDTOS = brandService.pageBrands(key, page, size);

        return ResponseEntity.ok(brandDTOS);
    }

    //根据分类id查询品牌
    @GetMapping("/of/category")
    public ResponseEntity<List<BrandDTO>> queryBrandByCid(@RequestParam("id") Integer id) {
        List<BrandDTO> list = brandService.queryBrandByCid(id);
        return ResponseEntity.ok(list);
    }

    //新增品牌
    @PostMapping
    public ResponseEntity<Void> insertBrand( BrandDTO brandDTO) {
        brandService.insertBrand(brandDTO);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    //更新品牌
    @PutMapping
    public ResponseEntity<Void> putBrand( BrandDTO brandDTO){
        brandService.putBrand(brandDTO);
        return ResponseEntity.ok().build();
    }

    //删除品牌
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteById(
            @PathVariable("id")Long id){

        this.brandService.deleteById(id);

        return ResponseEntity.ok().build();
    }

}